package ngames.com.sushitv.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import ngames.com.sushitv.R;
import ngames.com.sushitv.autobahn.WebSocketConnection;
import ngames.com.sushitv.autobahn.WebSocketConnectionHandler;
import ngames.com.sushitv.autobahn.WebSocketException;
import ngames.com.sushitv.base.BaseActivity;
import ngames.com.sushitv.tools.LogUtil;

public class ChatActivity extends BaseActivity {
    EditText mInputEdt;
    Button mSendBtn;
    TextView mMsgTv;
    private WebSocketConnection mConnection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        mInputEdt = (EditText) findViewById(R.id.edt_mesg);
        mSendBtn = (Button) findViewById(R.id.btn_send);
        mMsgTv = (TextView) findViewById(R.id.tvx_msg);
        mConnection = new WebSocketConnection();
        initWebSocket();

        mSendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg = null;
                if (mConnection.isConnected()) {
                    msg = mInputEdt.getText().toString();
                    mConnection.sendTextMessage(mInputEdt.getText().toString());
                }
                LogUtil.d("ChatActivity", "sendTextMessage msg = " + msg);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConnection.isConnected()) {
            mConnection.disconnect();
        }
    }

    private void initWebSocket() {
        String url = "ws://10.10.1.120:3456";
        try {
            mConnection.connect(url, new WebSocketConnectionHandler() {
                @Override
                public void onOpen() {
                    LogUtil.d("ChatActivity", "onOpen() WebSocket open");
                }

                @Override
                public void onTextMessage(String text) {
                    LogUtil.d("ChatActivity", "onTextMessage() " + text);
                    mMsgTv.setText(text);
                }

                @Override
                public void onClose(int code, String reason) {
                    LogUtil.d("ChatActivity", "onClose() code = " + code + ", reason = " + reason);

                }
            });
        } catch (WebSocketException e) {
            LogUtil.d("ChatActivity", "WebSocketException = " + e.toString());
        }
    }
}
